<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item label="员工工号" prop="jobNumber">
        <el-select 
          v-model="formData.jobNumber"
          filterable
          remote 
          placeholder="请选择员工工号"
          :remote-method="remoteJobNumberMethod"
          :loading="staffLoading"
          @change="changeJobNumber"
        >
          <el-option
            v-for="item in staffList"
            :key="item.jobNumber"
            :label="item.jobNumber"
            :value="item.jobNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="staffName">
        <el-select 
          v-model="staffName"
          filterable
          remote 
          placeholder="请选择员工姓名"
          :remote-method="remoteStaffNameMethod"
          :loading="staffLoading"
          @change="changeName"
          value-key="jobNumber"
        >
          <el-option
            v-for="item in staffList"
            :key="item.jobNumber"
            :label="item.staffName"
            :value="{ staffName: item.staffName, jobNumber: item.jobNumber }"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="dictPost">
        <el-select
          v-model="formData.dictPost"
          placeholder=""
          clearable
          class="!w-220px"
          disabled
        >
          <el-option
            v-for="dict, index in getIntDictOptions('config_post')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班组编码" prop="teamCode">
        <el-input
          class="!w-220px"
          v-model="formData.teamCode"
          placeholder=""
          disabled
        />
      </el-form-item>
      <el-form-item label="所属班组" prop="teamName">
        <el-input
          class="!w-220px"
          v-model="formData.teamName"
          placeholder=""
          disabled
        />
      </el-form-item>
      <el-form-item label="人员类别" prop="dictStaffType">
        <el-select
          class="!w-220px"
          v-model="formData.dictStaffType"
          placeholder=""
          disabled
        >
          <el-option
            v-for="dict, index in getIntDictOptions('config_staff_type')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="统计周期" prop="statisticalPeriodStart">
        <el-date-picker
          v-model="formData.statisticsDate"
          type="daterange"
          value-format="YYYY-MM-DD"
          start-placeholder="周期开始日期"
          end-placeholder="统计周期结束日期"
          style="width: auto"
          @change="changeAttendance"
        />
      </el-form-item>
      <el-form-item label="总出勤天数" prop="totalAttendanceSkyNumber">
        <el-input-number
          :min="0"
          v-model="formData.totalAttendanceSkyNumber"
          placeholder="请输入总出勤天数"
          clearable
          @change="changeAttendance"
          class="!w-220px"
          :disabled="!formData.statisticsDate || !formData.statisticsDate.length"
          :precision="2"
        />
      </el-form-item>
      <el-form-item label="计件工资" prop="pieceRate">
        <el-input
          class="!w-220px"
          v-model="formData.pieceRate"
          placeholder=""
          disabled
        />
      </el-form-item>
      <el-form-item label="绩效考核分数" prop="performanceAssessScore">
        <el-input-number
          :precision="2"
          class="!w-220px"
          v-model="formData.performanceAssessScore"
          placeholder="请输入绩效考核分数"
          clearable
          @change="setTotal"
        />
      </el-form-item>
      <el-form-item label="厂内加班小时" prop="insideFactoryOvertimeHour">
        <el-input-number
          :precision="2"
          :min="0"
          class="!w-220px"
          v-model="formData.insideFactoryOvertimeHour"
          placeholder="请输入厂内加班小时"
          clearable
          @change="setInsideSalary"
        />
      </el-form-item>
      <el-form-item label="加班工资(H)" prop="overtimeSalary">
        <el-input-number
          :precision="4"
          :min="0"
          class="!w-220px"
          v-model="formData.overtimeSalary"
          placeholder="请输入加班工资(H)"
          clearable
          @change="setInsideSalary"
        />
      </el-form-item>
      <el-form-item label="厂内加班工资" prop="insideFactoryOvertimeWage">
        <el-input
          class="!w-220px"
          v-model="formData.insideFactoryOvertimeWage"
          placeholder=""
          disabled
        />
      </el-form-item>
      <el-form-item label="班组长补贴" prop="leaderSubsidy">
        <el-input
          :precision="2"
          :min="0"
          class="!w-220px"
          v-model="formData.leaderSubsidy"
          placeholder="请输入班组长补贴"
          clearable
          @change="setTotal"
        />
      </el-form-item>
      <el-form-item label="奖惩金额" prop="rewardsPunishments">
        <el-input class="!w-220px" v-model="formData.rewardsPunishments" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="合计工资" prop="totalWage">
        <el-input class="!w-220px" v-model="formData.totalWage" placeholder="" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as StatementDimissionWageApi from '@/api/payroll/statementSearch/statementDimissionWage'
import * as ComponentApi from '@/api/componentApi/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  jobNumber: undefined,
  staffName: undefined,
  teamCode: undefined,
  teamName: undefined,
  performanceAssessScore: 100,
  totalAttendanceSkyNumber: undefined,
  insideFactoryOvertimeHour: undefined,
  dictStaffType: undefined,
  pieceRate: undefined,
  insideFactoryOvertimeWage: undefined,
  leaderSubsidy: undefined,
  rewardsPunishments: undefined,
  totalWage: undefined,
  overtimeSalary: undefined,
  statisticsDate: [],
  statisticalPeriodStart: undefined,
  statisticalPeriodEnd: undefined,
  dictPost: undefined,
  creatorName: undefined,
  updaterName: undefined
})
const formRules = reactive({
  jobNumber: [{ required: true, message: '员工工号不能为空', trigger: 'blur' }],
  staffName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  performanceAssessScore: [{ required: true, message: '绩效考核分数不能为空', trigger: 'blur' }],
  totalAttendanceSkyNumber: [{ required: true, message: '总出勤天数不能为空', trigger: 'blur' }],
  insideFactoryOvertimeHour: [{ required: true, message: '厂内加班小时不能为空', trigger: 'blur' }],
  leaderSubsidy: [{ required: true, message: '班组长补贴不能为空', trigger: 'blur' }],
  overtimeSalary: [{ required: true, message: '加班工资(H)不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

interface StaffType {
  staffName: string
  jobNumber: string
}
const staffList = ref<StaffType[]>([])
const staffName = ref<StaffType>()
const staffLoading = ref(false)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await StatementDimissionWageApi.getStatementDimissionWage(id)
      formData.value = data
      formData.value.statisticsDate = [data.statisticalPeriodStart, data.statisticalPeriodEnd]
      // 姓名回显
      staffName.value = {
        jobNumber: data.jobNumber,
        staffName: data.staffName
      }
      // 姓名回显选项
      staffList.value = [{
        jobNumber: data.jobNumber,
        staffName: data.staffName
      }]
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 通过姓名查询员工列表
const remoteStaffNameMethod = async (staffName: string) => {
  staffList.value = await ComponentApi.getStaffList(staffName)
}

// 通过工号查询员工列表
const remoteJobNumberMethod = async (jobNumber: string) => {
  staffList.value = await ComponentApi.getStaffList(jobNumber)
}

// 点击姓名
const changeName = async (staffObj: StaffType) => {
  const data = await ComponentApi.getStaffList(staffObj.staffName)
  formData.value.jobNumber = data[0].jobNumber
  formData.value.staffName = data[0].staffName
  formData.value.dictPost = data[0].dictPost
  formData.value.teamCode = data[0].teamCode
  formData.value.teamName = data[0].teamName
  formData.value.dictStaffType = data[0].dictStaffType
}

// 点击工号
const changeJobNumber = async (jobNumber: string) => {
  const data = await ComponentApi.getStaffList(jobNumber)
  formData.value.staffName = data[0].staffName
  formData.value.dictPost = data[0].dictPost
  formData.value.teamCode = data[0].teamCode
  formData.value.teamName = data[0].teamName
  formData.value.dictStaffType = data[0].dictStaffType
}

// 获取计件工资和奖惩金额
const changeAttendance = async () => {
  if (!formData.value.jobNumber) {
    message.notifyError('请输入工号')
    return
  }
  if (!formData.value.staffName) {
    message.notifyError('请输入姓名')
    return
  }
  const params = {
    jobNumber: formData.value.jobNumber,
    staffName: formData.value.staffName,
    statisticalPeriodStart: formData.value.statisticsDate[0],
    statisticalPeriodEnd: formData.value.statisticsDate[1],
    totalAttendanceSkyNumber: formData.value.totalAttendanceSkyNumber
  }
  // 统计周期和总出勤天数同时填写
  if (formData.value.totalAttendanceSkyNumber !== undefined && formData.value.totalAttendanceSkyNumber != 0 && formData.value.statisticsDate.length) {
    const data = await StatementDimissionWageApi.getStatementDimissionWageSalaryAward(params)
    formData.value.pieceRate = data.pieceRate
    formData.value.rewardsPunishments = data.rewardsPunishments
    setTotal()
  }
}

// 计算厂内加班工资
const setInsideSalary = () => {
  formData.value.insideFactoryOvertimeWage = 
    // 厂内加班小时
    parseFloat(formData.value.insideFactoryOvertimeHour || 0) * 
    // 加班工资(H)
    parseFloat(formData.value.overtimeSalary || 0)
    setTotal()
}

// 计算合计工资
const setTotal = () => {
  console.log(parseFloat(formData.value.performanceAssessScore))
  formData.value.totalWage = 
    // 厂内加班工资
    parseFloat(formData.value.insideFactoryOvertimeWage || 0) +
    // 班组长补贴
    parseFloat(formData.value.leaderSubsidy || 0) +
    // 奖惩金额
    parseFloat(formData.value.rewardsPunishments || 0) +
    // 计件工资 * 0.8
    parseFloat(formData.value.pieceRate || 0) * 0.8 +
    // 计件工资 * 0.2 *绩效考核分数 / 100
    parseFloat(formData.value.pieceRate || 0) * 0.2 * 
    parseFloat(formData.value.performanceAssessScore || 0) / 100
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StatementDimissionWageApi.StatementDimissionWageVO
    data.statisticalPeriodStart =  formData.value.statisticsDate[0]
    data.statisticalPeriodEnd = formData.value.statisticsDate[1]
    if (formType.value === 'create') {
      await StatementDimissionWageApi.createStatementDimissionWage(data)
      message.success(t('common.createSuccess'))
    } else {
      await StatementDimissionWageApi.updateStatementDimissionWage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    jobNumber: undefined,
    staffName: undefined,
    teamCode: undefined,
    teamName: undefined,
    performanceAssessScore: 100,
    totalAttendanceSkyNumber: undefined,
    insideFactoryOvertimeHour: undefined,
    dictStaffType: undefined,
    pieceRate: undefined,
    insideFactoryOvertimeWage: undefined,
    leaderSubsidy: undefined,
    rewardsPunishments: undefined,
    totalWage: undefined,
    overtimeSalary: undefined,
    statisticsDate: [],
    statisticalPeriodStart: undefined,
    statisticalPeriodEnd: undefined,
    dictPost: undefined,
    creatorName: undefined,
    updaterName: undefined
  }
  formRef.value?.resetFields()
}
</script>
